use crate::{components, dao};
use crate::models::models::components::v2ray::subscription::{ComponentV2raySubscription, ComponentV2raySubscriptionLastUpdateState};
use crate::runtime::response::MagicBoxResponse;
use crate::runtime::result::MagicBoxResult;

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_update_subscription(subscription: ComponentV2raySubscription) -> MagicBoxResult<MagicBoxResponse<()>> {
    let servers = components::v2ray::subscription::fetch_servers(&subscription.url).await;
    if servers.is_err() {
        let result = dao::components::v2ray::subscription::update_last_update_time(&subscription, chrono::Utc::now().timestamp(), ComponentV2raySubscriptionLastUpdateState::Failed);
        if result.is_err() {
            log::error!("更新订阅更新状态失败: {}", result.unwrap_err().to_string());
        }

        return Err(servers.unwrap_err());
    }

    let servers = servers.unwrap();
    for server in servers {
        let exists = dao::components::v2ray::server::get_server_with_tag(server.tag.as_str())?;
        dao::components::v2ray::server::save_server_config(server, exists.is_some())?;
    }

    let result = dao::components::v2ray::subscription::update_last_update_time(&subscription, chrono::Utc::now().timestamp(), ComponentV2raySubscriptionLastUpdateState::Success);
    if result.is_err() {
        log::error!("更新订阅更新状态失败: {}", result.unwrap_err().to_string());
    }

    Ok(MagicBoxResponse::new_empty_success())
}